from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator
from django.db import transaction
from django.utils import timezone
from decimal import Decimal
import json

from .models import (
    PhoneNumber, Plan, PhonePlan, Balance,
    Payment, UsageRecord, UserProfile
)
from .forms import (
    CustomUserCreationForm, PhoneNumberForm, PlanSelectionForm,
    PaymentForm, UserProfileForm, PhoneNumberSwitchForm
)


def home(request):
    """首页"""
    if request.user.is_authenticated:
        return redirect('mobile_app:dashboard')
    return render(request, 'mobile_app/home.html')


@login_required
def dashboard(request):
    """仪表板 - 显示当前用户的主号码信息"""
    try:
        # 获取用户的主号码
        primary_phone = PhoneNumber.objects.filter(
            user=request.user,
            is_primary=True
        ).first()

        if not primary_phone:
            # 如果没有主号码，获取第一个号码
            primary_phone = PhoneNumber.objects.filter(user=request.user).first()

        context = {
            'primary_phone': primary_phone,
        }

        if primary_phone:
            # 获取余额信息
            try:
                balance = primary_phone.balance
            except Balance.DoesNotExist:
                balance = Balance.objects.create(phone_number=primary_phone)

            # 获取套餐信息
            try:
                phone_plan = primary_phone.phone_plan
            except PhonePlan.DoesNotExist:
                phone_plan = None

            # 获取最近的缴费记录
            recent_payments = Payment.objects.filter(
                phone_number=primary_phone
            ).order_by('-payment_time')[:5]

            context.update({
                'balance': balance,
                'phone_plan': phone_plan,
                'recent_payments': recent_payments,
            })

        return render(request, 'mobile_app/dashboard.html', context)

    except Exception as e:
        messages.error(request, f'加载仪表板时出错: {str(e)}')
        return render(request, 'mobile_app/dashboard.html')


@login_required
def phone_management(request):
    """手机号码管理"""
    phone_numbers = PhoneNumber.objects.filter(user=request.user)
    phone_form = PhoneNumberForm()

    if request.method == 'POST':
        if 'add_phone' in request.POST:
            phone_form = PhoneNumberForm(request.POST)
            
            if phone_form.is_valid():
                # 重新查询当前用户的号码数量，确保计数准确
                current_count = PhoneNumber.objects.filter(user=request.user).count()

                # 检查用户是否已经添加了这个号码
                number = phone_form.cleaned_data['number']
                
                # 检查号码是否已被其他用户注册
                if PhoneNumber.objects.filter(number=number).exists():
                    existing_phone = PhoneNumber.objects.filter(number=number).first()
                    if existing_phone.user == request.user:
                        messages.error(request, '您已经添加过这个手机号码')
                    else:
                        messages.error(request, '该手机号码已被其他用户注册')
                elif current_count >= 5:
                    messages.error(request, '每个用户最多只能添加5个手机号码')
                else:
                    try:
                        phone_number = phone_form.save(commit=False)
                        phone_number.user = request.user
                        # 如果是第一个号码，设为主号码
                        if current_count == 0:
                            phone_number.is_primary = True
                        phone_number.save()
                        
                        # 创建对应的余额记录
                        Balance.objects.create(phone_number=phone_number)
                        
                        messages.success(request, f'成功添加手机号码 {phone_number.number}')
                        return redirect('mobile_app:phone_management')
                    except Exception as e:
                        messages.error(request, f'添加号码失败: {str(e)}')
            else:
                # 表单验证失败，显示错误信息
                for field, errors in phone_form.errors.items():
                    for error in errors:
                        messages.error(request, f'{phone_form.fields[field].label}: {error}')

        elif 'set_primary' in request.POST:
            phone_id = request.POST.get('phone_id')
            try:
                phone = get_object_or_404(PhoneNumber, id=phone_id, user=request.user)
                # 取消其他号码的主号码状态
                PhoneNumber.objects.filter(user=request.user, is_primary=True).update(is_primary=False)
                # 设置当前号码为主号码
                phone.is_primary = True
                phone.save()
                messages.success(request, f'已将 {phone.number} 设为主号码')
            except Exception as e:
                messages.error(request, f'设置主号码失败: {str(e)}')
            return redirect('mobile_app:phone_management')

        elif 'delete_phone' in request.POST:
            phone_id = request.POST.get('phone_id')
            try:
                phone = get_object_or_404(PhoneNumber, id=phone_id, user=request.user)
                phone_number = phone.number
                phone.delete()
                messages.success(request, f'已删除手机号码 {phone_number}')
            except Exception as e:
                messages.error(request, f'删除号码失败: {str(e)}')
            return redirect('mobile_app:phone_management')

    context = {
        'phone_numbers': phone_numbers,
        'phone_form': phone_form,
    }
    return render(request, 'mobile_app/phone_management.html', context)


@login_required
def plan_management(request, phone_id):
    """套餐管理"""
    phone = get_object_or_404(PhoneNumber, id=phone_id, user=request.user)

    try:
        current_plan = phone.phone_plan
    except PhonePlan.DoesNotExist:
        current_plan = None

    plans = Plan.objects.filter(is_active=True)
    plan_form = PlanSelectionForm()

    if request.method == 'POST':
        plan_form = PlanSelectionForm(request.POST)
        if plan_form.is_valid():
            selected_plan = plan_form.cleaned_data['plan']

            # 更新或创建套餐关联
            phone_plan, created = PhonePlan.objects.get_or_create(
                phone_number=phone,
                defaults={'plan': selected_plan, 'is_active': True}
            )

            if not created:
                phone_plan.plan = selected_plan
                phone_plan.is_active = True
                phone_plan.save()

            # 更新余额信息
            balance, created = Balance.objects.get_or_create(phone_number=phone)
            balance.update_allowance()

            messages.success(request, f'成功为 {phone.number} 设置套餐: {selected_plan.name}')
            return redirect('mobile_app:plan_management', phone_id=phone_id)

    context = {
        'phone': phone,
        'current_plan': current_plan,
        'plans': plans,
        'plan_form': plan_form,
    }
    return render(request, 'mobile_app/plan_management.html', context)


@login_required
def balance_query(request, phone_id):
    """余额查询"""
    phone = get_object_or_404(PhoneNumber, id=phone_id, user=request.user)

    try:
        balance = phone.balance
    except Balance.DoesNotExist:
        balance = Balance.objects.create(phone_number=phone)

    try:
        phone_plan = phone.phone_plan
    except PhonePlan.DoesNotExist:
        phone_plan = None

    # 获取使用记录
    usage_records = UsageRecord.objects.filter(phone_number=phone).order_by('-usage_time')[:10]

    # 计算使用量
    data_used = 0
    voice_used = 0
    sms_used = 0

    if phone_plan:
        data_used = phone_plan.plan.data_allowance - balance.data_remaining
        voice_used = phone_plan.plan.voice_allowance - balance.voice_remaining
        sms_used = phone_plan.plan.sms_allowance - balance.sms_remaining

    context = {
        'phone': phone,
        'balance': balance,
        'phone_plan': phone_plan,
        'usage_records': usage_records,
        'data_used': data_used,
        'voice_used': voice_used,
        'sms_used': sms_used,
    }
    return render(request, 'mobile_app/balance_query.html', context)


@login_required
def payment(request, phone_id):
    """缴费功能"""
    phone = get_object_or_404(PhoneNumber, id=phone_id, user=request.user)
    payment_form = PaymentForm()

    if request.method == 'POST':
        payment_form = PaymentForm(request.POST)
        if payment_form.is_valid():
            with transaction.atomic():
                payment = payment_form.save(commit=False)
                payment.phone_number = phone
                payment.save()

                messages.success(request, f'缴费成功！已为 {phone.number} 充值 ¥{payment.amount}')
                return redirect('mobile_app:balance_query', phone_id=phone_id)

    context = {
        'phone': phone,
        'payment_form': payment_form,
    }
    return render(request, 'mobile_app/payment.html', context)


@login_required
def profile(request):
    """用户资料管理"""
    try:
        user_profile = request.user.profile
    except UserProfile.DoesNotExist:
        user_profile = UserProfile.objects.create(user=request.user)

    if request.method == 'POST':
        profile_form = UserProfileForm(request.POST, request.FILES, instance=user_profile)
        if profile_form.is_valid():
            profile_form.save()
            messages.success(request, '资料更新成功')
            return redirect('mobile_app:profile')
    else:
        profile_form = UserProfileForm(instance=user_profile)

    context = {
        'profile_form': profile_form,
        'user_profile': user_profile,
    }
    return render(request, 'mobile_app/profile.html', context)


@login_required
def switch_phone(request):
    """切换查询号码"""
    phone_numbers = PhoneNumber.objects.filter(user=request.user)

    if request.method == 'POST':
        phone_id = request.POST.get('phone_id')
        if phone_id:
            phone = get_object_or_404(PhoneNumber, id=phone_id, user=request.user)
            # 将选中的号码设为主号码
            PhoneNumber.objects.filter(user=request.user, is_primary=True).update(is_primary=False)
            phone.is_primary = True
            phone.save()
            messages.success(request, f'已切换到号码 {phone.number}')
            return redirect('mobile_app:dashboard')

    context = {
        'phone_numbers': phone_numbers,
    }
    return render(request, 'mobile_app/switch_phone.html', context)


@login_required
@csrf_exempt
@require_http_methods(["POST"])
def simulate_usage(request):
    """模拟使用流量/语音"""
    try:
        data = json.loads(request.body)
        phone_id = data.get('phone_id')
        usage_type = data.get('usage_type')
        amount = int(data.get('amount', 0))

        phone = get_object_or_404(PhoneNumber, id=phone_id, user=request.user)
        balance = phone.balance

        # 检查剩余额度
        if usage_type == 'data' and balance.data_remaining < amount:
            return JsonResponse({'success': False, 'message': '流量不足'})
        elif usage_type == 'voice' and balance.voice_remaining < amount:
            return JsonResponse({'success': False, 'message': '语音额度不足'})
        elif usage_type == 'sms' and balance.sms_remaining < amount:
            return JsonResponse({'success': False, 'message': '短信额度不足'})

        # 创建使用记录
        UsageRecord.objects.create(
            phone_number=phone,
            usage_type=usage_type,
            amount_used=amount
        )

        # 更新剩余额度
        if usage_type == 'data':
            balance.data_remaining -= amount
        elif usage_type == 'voice':
            balance.voice_remaining -= amount
        elif usage_type == 'sms':
            balance.sms_remaining -= amount

        balance.save()

        return JsonResponse({
            'success': True,
            'message': '使用记录已更新',
            'data_remaining': balance.data_remaining,
            'voice_remaining': balance.voice_remaining,
            'sms_remaining': balance.sms_remaining,
        })

    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})


def register_view(request):
    """用户注册"""
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            # 创建用户资料
            UserProfile.objects.create(user=user)
            login(request, user)
            messages.success(request, '注册成功！')
            return redirect('mobile_app:dashboard')
    else:
        form = CustomUserCreationForm()

    return render(request, 'mobile_app/register.html', {'form': form})


def login_view(request):
    """用户登录"""
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        from django.contrib.auth import authenticate
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            messages.success(request, '登录成功！')
            return redirect('mobile_app:dashboard')
        else:
            messages.error(request, '用户名或密码错误')

    return render(request, 'mobile_app/login.html')


def logout_view(request):
    """用户登出"""
    logout(request)
    messages.info(request, '已成功登出')
    return redirect('mobile_app:home')
